package com.dodock.banglapapers.server.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsListBBCBangla extends DefaultHandler implements DDNNewsListInterface {

	public static final String TAG_ENTRY = "entry";
	public static final String TAG_ENTRY_TITLE = "title";
	public static final String TAG_ENTRY_LINK = "link";
	public static final String TAG_ENTRY_ID = "dc:identifier";
	public static final String TAG_ENTRY_IMAGE = "img";
	
	JsonArray array;
	boolean entryParsing;
	String lastTagName;
	JsonObject news;
	private String characters;
	
	@Override
	public String GenerateNewsList(String categoryid) {
		
		try{
			if(categoryid.equals("top")){
				return generateNewsListFromRssFeed("http://www.bbc.co.uk/bengali/index.xml");
			}
			else if(categoryid.equals("special")){
				return generateNewsListFromRssFeed("http://www.bbc.co.uk/bengali/in_depth/index.xml");
			}	
		}
		catch(Exception ex){
			return "[]";
		}
		
		
		return "[]";
	}

	
	private String generateNewsListFromRssFeed(String feedUrl) throws IOException, SAXException, ParserConfigurationException{
		array = new JsonArray();
		entryParsing = false;
		lastTagName = null;
		
		URL url = new URL(feedUrl);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
		StringBuilder xmlString = new StringBuilder();
		String line;
        while ((line = reader.readLine()) != null) {
        	//line = line.replaceAll("-&-", "-&amp;-");
        	xmlString.append(line);
        }
        reader.close();
        
        
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(new java.io.ByteArrayInputStream(xmlString.toString().getBytes("UTF-8")), this);
		
		return array.toString();
	}
	
	
	public void startElement(String namespaceURI, 
            String localName,
            String qualifiedName,
            Attributes attributes) 
            		throws SAXException {
			lastTagName = qualifiedName;
			if (lastTagName.equalsIgnoreCase(TAG_ENTRY)) {
				entryParsing = true;
				news = new JsonObject();
			}
			else if (lastTagName.equalsIgnoreCase(TAG_ENTRY_LINK)) {
				if(entryParsing){
					news.addProperty("sharelink", attributes.getValue("href"));
				}
			}
			else if (lastTagName.equalsIgnoreCase(TAG_ENTRY_IMAGE)) {
				if(entryParsing){
					news.addProperty("image", attributes.getValue("src"));
				}
			}
	}
	
	public void endElement(String namespaceURI, 
            String simpleName,
            String qualifiedName) 
            throws SAXException {
		
		if (qualifiedName.equalsIgnoreCase(TAG_ENTRY)) {
			entryParsing = false;
			String shareLink = news.get("sharelink").toString(); 
			if(news.get("sharelink") != null && news.get("sharelink").toString().contains("http://www.bbc.co.uk/bengali/news/")){
				array.add(news);
			}
			else{
				System.out.println(news.get("sharelink").toString());
			}
		} 
		lastTagName = null;
	}
	
	public void characters(char buf[], int offset, int len) 
            throws SAXException {
            characters = new String(buf, offset, len);
            
            if (lastTagName != null) {
				if (lastTagName.equalsIgnoreCase(TAG_ENTRY_TITLE)) {
					if (entryParsing) {
						news.addProperty("title", characters);
					}
				} else if (lastTagName.equalsIgnoreCase(TAG_ENTRY_ID)) {
					if (entryParsing) {
						news.addProperty("id", characters);
					}
				} 
			}
    }
	
}
